using System.Text.RegularExpressions;
using Microsoft.AspNetCore.Mvc.Filters;
using SqlSugar;
using Vin.Extension.Framework.Aop;
using Vin.Extension.Framework.Monitor.Extension;
using Vin.Extension.Framework.Monitor.Options;
using Vin.Extension.Framework.Monitor.ServiceInterface;
using Vin.Extension.SqlSugar;
using Vin.Extension.SqlSugar.Utils;
using Vin.Tool.AspNetCore.Singleton;
using Vin.Tool.Core.NetCategory;

namespace Vin.Extension.Framework.Monitor.Filters;

/// <summary>
/// 总是会在 IAuthorizationFilter 授权之后执行，导致在授权之前的操作无法记录日志
/// </summary>
public class RequestLogAttribute : VinLogAttribute
{

    public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
    {
        if (context.HttpContext.IsExecuteRequestLog())
        {
            await next();
            return;
        }
        var monitorOptions = VinApp.GetConfig<MonitorOption>();

        if (monitorOptions.IgnoreRequestPath.Any(x => Regex.IsMatch(context.HttpContext.Request.Path, x)))
        {
            await next();
            return;
        }

        if (monitorOptions.IgnoreRequestPath.Any(x => context.HttpContext.Request.Path.Value?.Contains(x) == true))
        {
            await next();
            return;
        }

        var sysRequestLogService = VinApp.GetRequiredServiceByHttpContext<ISysRequestLogService>();
        var sqlSugarClient = VinApp.GetRequiredServiceByHttpContext<ISqlSugarClient>();

        #region 记录日志

        List<string> sqlList = new();
        if (sqlSugarClient is VinSqlSugarClient client)
        {
            client.VinAop.OnLogExecuting = (db, sql, pars) =>
            {
                sqlList.Add(VinSqlSugarUtilsMethods.GetAppendSql(sql, pars));
            };
        }

        #endregion

        var (httpContextInfo, costTime) = await GetResult(context, next);

        await sysRequestLogService.PreSaveAsync(httpContextInfo, costTime, sqlList);
    }
}